"""
自定义用户传统身份认证的认证后端
目的：实现用户名或手机号，多账号登陆
"""

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q # Q将多个条件，构建成互为"或"的条件
from .models import User


# 继承Django默认的认证后端
class UsernameMobileAuthBackend(ModelBackend):

    # 重写authenticate方法
    # 原因：默认的authenticate方法，只会根据username字段去过滤查找用户
    def authenticate(self, request, username=None, password=None, **kwargs):
        # 允许多账号登陆的情况下，前端传来的"username"有可能是用户名也有可能是手机号

        # try:
        #     # 1、先按用户名查找
        #     user = User.objects.get(
        #         # username=="18588269037" or mobile=="18588269037"
        #         Q(username=username) |  Q(mobile=username) | Q(email=username)
        #     )
        # except User.DoesNotExist as e:
        #     return None # 用户名找不到，返回None表示认证失败
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist as e:
            print(e)

            try:
                user = User.objects.get(mobile=username)
            except User.DoesNotExist as e:
                print(e)
                return None



        # 3、某一个找到了，再校验密码
        if user.check_password(password):
            return user















